<?php
namespace Home\Model;
use Think\Model;
use Think\Crypt;
class MemberModel extends Model {
		protected $_validate = array(
				array('username','/^[\w\x80-\xff]{3,15}$/','用户名格式不正确！',1), //默认情况下用正则进行验证
				array('email','email','邮箱格式不正确！',1,'regex',1), //默认情况下用正则进行验证
				array('agreement','require','改须同意协议才能注册',1,'regex',1), //默认情况下用正则进行验证
				array('username','','用户名已经存在！',1,'unique',1), // 在修改的时候验证name字段是否唯一
				array('captcha','verify','验证码不正确',1,'callback'),
		);
	
	//处理图片验证码
	public function verify($code){
			    $verify = new \Think\Verify();
				return $verify->check($code);
		}
		
		
		public function _before_insert($data,$option){
			
		
		
		}
		
		//向注册用户提供的注册邮箱发送注册验证邮件
		public function _after_insert($data,$option){
			$content="点击以下链接，完成商城帐号验证：http://localhost/shop/index.php/home/User/check_email/es/".$data['mail_str'];
			SendMail($data['email'],'美丽说商城帐号验证',$content);
		}
		
		
		//处理用户登录的功能
		public function login(){
			$password=$this->password;
			$use=$this->username;
			$user=$this->where(array('username'=>$use))->find();
			$res=D('member')->where(array('username'=>$use))->find();
			if($res){
				if($res['password']==md5($password)){
					session('id',$res['id']);
					session('username',$res['username']);
					if(I('remember')){
						$des_key=C('DES_KEY');
						$username=Crypt::encrypt($use,$des_key);
						$password=Crypt::encrypt($password,$des_key);
						setcookie('username',$username,time()+60*60*3,'/');
						setcookie('password',$password,time()+60*60*3,'/');
					}
					$memberLevel=D('memberLevel');
					$memberLevel=$memberLevel->where("{$user['points']} BETWEEN points_min AND points_max")->find();
					//dump($memberLevel);die;
					session('rate',$memberLevel['rate']);
					session('levelId',$memberLevel['id']);
					return true;
				}else{
					
					return false;
				}
			}
			return false;
		}
		
		//处理用户退出功能，清空session里面的用户数据
		public function logout(){
			session(null);
			setcookie('username','',1,'/');
			setcookie('password','',1,'/');
		}
	
}